﻿using Core.FrameWork.Commons.App;
using Core.FrameWork.Commons.Extensions;
using Core.FrameWork.Commons.Loging.Model;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace Core.FrameWork.Commons.Loging
{
    /// <summary>
    /// 日志锁
    /// </summary>
    public class LogLockHelper
    {
        static ReaderWriterLockSlim LogWriteLock = new ReaderWriterLockSlim();
        static int WritedCount = 0;
        static int FailedCount = 0;
        static string _contentRoot = AppCenter.webHostEnvironment.ContentRootPath;

        public static void OutSql2Log(string rootPath, string filename, string[] dataParas, bool IsHeader = true)
        {
            try
            {
                //设置读写锁为写入模式独占资源，其他写入请求需要等待本次写入结束之后才能继续写入
                //注意：长时间持有读线程锁或写线程锁会使其他线程发生饥饿 (starve)。 为了得到最好的性能，需要考虑重新构造应用程序以将写访问的持续时间减少到最小。
                //      从性能方面考虑，请求进入写入模式应该紧跟文件操作之前，在此处进入写入模式仅是为了降低代码复杂度
                //      因进入与退出写入模式应在同一个try finally语句块内，所以在请求进入写入模式之前不能触发异常，否则释放次数大于请求次数将会触发异常
                LogWriteLock.EnterWriteLock();

                var path = Path.Combine(_contentRoot, "App_Data/" + rootPath);
                if (!Directory.Exists(path))
                {
                    Directory.CreateDirectory(path);
                }
                string logFilePath = Path.Combine(path, $@"{filename}.log");

                var now = DateTime.Now;
                string logContent = String.Join("\r\n", dataParas);
                if (IsHeader)
                {
                    logContent = (
                       "--------------------------------\r\n" +
                       DateTime.Now + "|\r\n" +
                       String.Join("\r\n", dataParas) + "\r\n"
                       );
                }

                File.AppendAllText(logFilePath, logContent);
                WritedCount++;
            }
            catch (Exception e)
            {
                Console.Write(e.Message);
                FailedCount++;
            }
            finally
            {
                //退出写入模式，释放资源占用
                //注意：一次请求对应一次释放
                //      若释放次数大于请求次数将会触发异常[写入锁定未经保持即被释放]
                //      若请求处理完成后未释放将会触发异常[此模式不下允许以递归方式获取写入锁定]
                LogWriteLock.ExitWriteLock();
            }
        }
        public static List<LogInfo> GetLogData(DateTime dateTime)
        {
            List<LogInfo> aopLogs = new List<LogInfo>();
            List<LogInfo> sqlLogs = new List<LogInfo>();
            List<LogInfo> ipsLogs = new List<LogInfo>();
            List<LogInfo> accessLogs = new List<LogInfo>();

            try
            {
                var aoplogContent = ReadLog(Path.Combine(_contentRoot, "App_Data", "AOPLog.log"), Encoding.UTF8);

                if (!string.IsNullOrEmpty(aoplogContent))
                {
                    aopLogs = aoplogContent.Split("--------------------------------")
                 .Where(d => !string.IsNullOrEmpty(d) && d != "\n" && d != "\r\n")
                 .Select(d => new LogInfo
                 {
                     Datetime = d.Split("|")[0].ToDateTime(),
                     Content = d.Split("|")[1]?.Replace("\r\n", "<br>"),
                     LogColor = "AOP",
                 }).ToList();
                }
            }
            catch (Exception) { }



            try
            {
                var sqllogContent = System.Text.Json.JsonSerializer.Deserialize<List<ReqEfLogInfo>>("[" + ReadLog(Path.Combine(_contentRoot, "App_Data", "SqlLog", $"SqlLog{dateTime.ToString("yyyy-MM-dd")}.log"), Encoding.UTF8) + "{}" + "]");

                sqllogContent = sqllogContent.Where(d => d.DateTime >= DateTime.Today).OrderByDescending(s=>s.DateTime).ToList();

                sqlLogs = sqllogContent.Select(d => new LogInfo
                {
                    Datetime = d.DateTime,
                    Content = $"DateTime:{d.DateTime}<br>Sql:【{d.Sql}】<br>",
                    LogColor = "Sql",
                }).ToList();
                if (sqlLogs != null)
                    aopLogs.AddRange(sqlLogs);
            }
            catch (Exception) { }
            try
            {

                var LogsAccess = System.Text.Json.JsonSerializer.Deserialize<List<UserAccessModel>>("[" + ReadLog(Path.Combine(_contentRoot, "App_Data", "RecordAccessLogs", $"RecordAccessLogs{dateTime.ToString("yyyy-MM-dd")}.log"), Encoding.UTF8) + "{}" + "]");

                LogsAccess = LogsAccess.Where(d => d.BeginTime.ToDateTime() >= DateTime.Today).ToList();

                accessLogs = LogsAccess.Select(d => new LogInfo
                {
                    Datetime = d.BeginTime.ToDateTime(),
                    Content = $"User:{d.User}<br>IP:{d.IP}<br>{d.API}",
                    LogColor = "ReqAccess",
                    IP= d.IP
                }).ToList();
                if (accessLogs != null)
                    aopLogs.AddRange(accessLogs);
            }
            catch (Exception)
            {
            }
            try
            {

                var LogsIp = System.Text.Json.JsonSerializer.Deserialize<List<RequestInfo>>("[" + ReadLog(Path.Combine(_contentRoot, "App_Data", "RequestIpInfoLog", $"RequestIpInfoLog{dateTime.ToString("yyyy-MM-dd")}.log"), Encoding.UTF8) + "{}" + "]");

                LogsIp = LogsIp.Where(d => d.Datetime.ToDateTime() >= DateTime.Today).ToList();

                ipsLogs = LogsIp.Select(d => new LogInfo
                {
                    Datetime = d.Datetime.ToDateTime(),
                    Content = $"IP:{d.Ip}<br>{d.Url}",
                    LogColor = "ReqIp",
                }).ToList();
                if (ipsLogs != null)
                    aopLogs.AddRange(ipsLogs);
            }
            catch (Exception)
            {
            }
            aopLogs = aopLogs.OrderByDescending(d => d.LogColor).ThenByDescending(d => d.Datetime).ToList();

            return aopLogs;
        }
        public static string ReadLog(string Path, Encoding encode)
        {
            string s = "";
            try
            {
                LogWriteLock.EnterReadLock();

                if (!System.IO.File.Exists(Path))
                    s = "";
                else
                {
                    StreamReader f2 = new StreamReader(Path, encode);
                    s = f2.ReadToEnd();
                    f2.Close();
                    f2.Dispose();
                }
            }
            catch (Exception ex)
            {
                NLogUtil.WriteAll(NLog.LogLevel.Error, LogType.Web, "接口读取日志错误", $"读取路径:【{Path}】", new Exception("接口读取日志错误", ex));
                FailedCount++;
            }
            finally
            {
                LogWriteLock.ExitReadLock();
            }
            return s;
        }
    }
}
